package com.bjtang.fileSync.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.bjtang.fileSync.util.FileCODEC;
import com.bjtang.fileSync.util.FileConfig;

/**
 * nio服务 bjtang 2024.1.12
 */
public class NIOServer {
	private static Logger logger = LogManager.getLogger("file-sync");
	// 线程池中工作线程的数目 public
	// 八个业务处理线程
	private static final int POOL_MULTIPLE = 8;

	public static void main(String[] args) throws IOException {
		// 启动nioServer
		start(Integer.valueOf(FileConfig.readConfig("port").trim()));
	}

	public static void start(int port) throws IOException {
		// 线程池
		ExecutorService executorService = Executors
				.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * POOL_MULTIPLE);
		// 服务器套接字通道
		ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
		// 非阻塞
		// serverSocketChannel.configureBlocking(true);
		// 绑定端口
		serverSocketChannel.socket().bind(new InetSocketAddress(port));
		logger.info("------开始工作-------");

		while (true) {
			// 等待客户端连接
			SocketChannel socketChannel = serverSocketChannel.accept();
			if (socketChannel != null)
				// 处理业务
				try {
					byte[] readChannel = FileCODEC.readChannel(socketChannel);
					SocketDto decoder = FileCODEC.decoder(readChannel);
					executorService.execute(new NonBlockingHandler(socketChannel, decoder));
				} catch (Exception e) {
					logger.error(e);
				}
		}
	}
}
